package com.jwsoft.manager.core.integration.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.core.helper.ApiContainer;
import com.bifang.module.base.core.helper.ApiModel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.vo.dygx.CbVO;
import com.jwsoft.manager.common.vo.dygx.DyJzzVO;
import com.jwsoft.manager.common.vo.eduSystemConfig.EduSystemConfigFuncQueryVO;
import com.jwsoft.manager.core.dao.model.EduLivePlace;
import com.jwsoft.manager.core.dao.model.EduSocialSecurity;
import com.jwsoft.manager.core.dao.service.EduLivePlaceService;
import com.jwsoft.manager.core.dao.service.EduSocialSecurityService;
import com.jwsoft.manager.core.integration.common.DygxIntegration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.common.vo.eduBdSbjzz.EduBdSbjzzVO;
import com.jwsoft.manager.common.vo.eduBdSbjzz.EduBdSbjzzKeyVO;
import com.jwsoft.manager.common.vo.eduBdSbjzz.EduBdSbjzzQueryVO;
import com.jwsoft.manager.core.integration.EduBdDataIntegration;
import com.jwsoft.manager.core.dao.service.EduBdSbjzzService;
import com.jwsoft.manager.core.dao.model.EduBdSbjzz;

/**
 * 数据比对信息表业务实现类
 *
 * @author zhiyuan
 * @since 2023-09-26
 */
@ApiService(funcCode = "eduBdData", title = "数据比对信息表")
public class EduBdDataIntegrationImpl implements EduBdDataIntegration {

    @Autowired
    public EduBdSbjzzService eduBdSbjzzService;

    @Autowired
    private EduLivePlaceService eduLivePlaceService;

    @Autowired
    private DygxIntegration dygxIntegration;

    @Override
    @OpApi(funcCode = "eduBdData0001", title = "数据比对信息表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduBdSbjzzVO> getList(EduBdSbjzzQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(10000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduBdSbjzz> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ObjectUtils.isEmpty(vo.getOptionFlag()),EduBdSbjzz::getOptionFlag,vo.getOptionFlag());
        List<EduBdSbjzz> list = eduBdSbjzzService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduBdSbjzz> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduBdSbjzzVO> resultList = Convert.toList(EduBdSbjzzVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduBdData0002", title = "数据比对信息表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduBdSbjzzVO getById(EduBdSbjzzKeyVO vo) {
        EduBdSbjzz entity = eduBdSbjzzService.getById(vo.getId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduBdSbjzzVO result = Convert.convert(EduBdSbjzzVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduBdData0003", title = "数据比对信息表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduBdSbjzzVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduBdData0004", title = "数据比对信息表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduBdData0004",
            operationName = "数据比对信息表新增",
            dataType = "id",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduBdSbjzzVO add(EduBdSbjzzVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduBdSbjzz entity = Convert.convert(EduBdSbjzz.class, vo);
        eduBdSbjzzService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setId(entity.getId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduBdData0005", title = "数据比对信息表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduBdData0005",
            operationName = "数据比对信息表修改",
            dataType = "id",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduBdSbjzzVO edit(EduBdSbjzzVO vo) {
        if (ObjectUtils.isEmpty(vo.getId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduBdSbjzz oldEntity = eduBdSbjzzService.getById(vo.getId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduBdSbjzz entity = Convert.convert(EduBdSbjzz.class, vo);
        eduBdSbjzzService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduBdData0006", title = "数据比对信息表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduBdData0006",
            operationName = "数据比对信息表删除",
            dataType = "id",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduBdSbjzzKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduBdSbjzz entity = eduBdSbjzzService.getById(vo.getId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduBdSbjzzService.removeById(vo.getId());
    }

    @Override
    @OpApi(funcCode = "eduBdData0007", title = "数据比对", funcType = FuncTypeEnum.update)
    public void dataComparison(EduBdSbjzzQueryVO vo) {
        vo.setOptionFlag(BoolEnum.FALSE.getType());
        Boolean isLastPage = false;
        //判断当前是否未最后一页
        if (!isLastPage){
            //去进行分页查询，
            PageInfo<EduBdSbjzzVO> pageInfo = this.getList(vo);
            List<EduBdSbjzzVO> eduBdSbjzzVOList = pageInfo.getList();
            for (EduBdSbjzzVO eduBdSbjzzVO : eduBdSbjzzVOList) {
                EduBdSbjzz eduBdSbjzz = new EduBdSbjzz();
                BeanUtils.copyProperties(eduBdSbjzzVO, eduBdSbjzz);
                eduBdSbjzz.setOptionFlag(BoolEnum.TRUE.getType());
                try {
                    //去查询是否有居住证
                    queryLivePlace(eduBdSbjzz,vo.getReqIp());
                } catch (Exception e) {
                    String errorMessage = e.getMessage();
                    if (errorMessage != null && errorMessage.length() > 100) {
                        errorMessage = errorMessage.substring(0, 100);
                    }
                    //错误异常处理
                    eduBdSbjzz.setOptionFlag("2");
                    eduBdSbjzz.setErrorRemark(errorMessage);
                }
                try {
                    //去查询是否有社保信息
                    querySocialSecurity(eduBdSbjzz,vo.getReqIp());

                } catch (Exception e) {
                    String errorMessage = e.getMessage();
                    if (errorMessage != null && errorMessage.length() > 100) {
                        errorMessage = errorMessage.substring(0, 100);
                    }
                    //错误异常处理
                    eduBdSbjzz.setOptionFlag("2");
                    eduBdSbjzz.setErrorRemark(errorMessage);
                }

                eduBdSbjzzService.updateById(eduBdSbjzz);
            }
            isLastPage = pageInfo.isIsLastPage();
        }

    }

    /**
     * 查询是否有社保信息
     * @param eduBdSbjzz
     */
    private void querySocialSecurity(EduBdSbjzz eduBdSbjzz,String ip) {
        if (StringUtils.isNotBlank(eduBdSbjzz.getFatherIdcard())){
            List<CbVO> grcbDy = dygxIntegration.getGrcbDy(eduBdSbjzz.getFatherIdcard(),ip);
            eduBdSbjzz.setFatherSb(BoolEnum.FALSE.getType());
            if (!ObjectUtils.isEmpty(grcbDy)){
                for (CbVO cbVO : grcbDy) {
                    if (cbVO.getAae140().equalsIgnoreCase("110")
                            && cbVO.getAac031().equalsIgnoreCase("1")
                            && cbVO.getAac008().equalsIgnoreCase("1")){
                        eduBdSbjzz.setFatherSb(BoolEnum.TRUE.getType());
                        break;
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(eduBdSbjzz.getMotherIdcard())){
            List<CbVO> grcbDy = dygxIntegration.getGrcbDy(eduBdSbjzz.getMotherIdcard(),ip);
            eduBdSbjzz.setMotherSb(BoolEnum.FALSE.getType());
            if (!ObjectUtils.isEmpty(grcbDy)){
                for (CbVO cbVO : grcbDy) {
                    if (cbVO.getAae140().equalsIgnoreCase("110")
                            && cbVO.getAac031().equalsIgnoreCase("1")
                            && cbVO.getAac008().equalsIgnoreCase("1")){
                        eduBdSbjzz.setMotherSb(BoolEnum.TRUE.getType());
                        break;
                    }
                }
            }

        }
    }

    /**
     * 查询是否有居住证信息
     * @param eduBdSbjzz
     */
    private void queryLivePlace(EduBdSbjzz eduBdSbjzz,String ip) {
        String compareDateStr = "20220101";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        if (StringUtils.isNotBlank(eduBdSbjzz.getFatherIdcard())){
            eduBdSbjzz.setFatherJzz(BoolEnum.FALSE.getType());
            QueryWrapper<EduLivePlace> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(EduLivePlace::getSfzh,eduBdSbjzz.getFatherIdcard());
            List<EduLivePlace> list = eduLivePlaceService.list(queryWrapper);
            if (!ObjectUtils.isEmpty(list)){
                for (EduLivePlace eduLivePlace : list) {
                    String qzrq = eduLivePlace.getQzrq();
                    try {
                        Date qzrqDate = dateFormat.parse(qzrq);
                        Date compareDate = dateFormat.parse(compareDateStr);
                        if (qzrqDate.compareTo(compareDate) >= 0) {
                            //表示居住证有效
                            eduBdSbjzz.setFatherJzz(BoolEnum.TRUE.getType());
                            break;
                        }
                    } catch (ParseException e) {

                    }
                }
            }
            if (BoolEnum.FALSE.getType().equalsIgnoreCase(eduBdSbjzz.getFatherJzz())){
                //去调用大数据接口查询
                List<DyJzzVO> dyJzz = dygxIntegration.getDyJzz(eduBdSbjzz.getFatherIdcard(),ip);
                for (DyJzzVO dyJzzVO : dyJzz) {
                    String qzrq = dyJzzVO.getQzrq();
                    try {
                        Date qzrqDate = dateFormat.parse(qzrq);
                        Date compareDate = dateFormat.parse(compareDateStr);
                        if (qzrqDate.compareTo(compareDate) >= 0) {
                            //表示居住证有效
                            eduBdSbjzz.setFatherJzz(BoolEnum.TRUE.getType());
                            break;
                        }
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }
            }


        }

        if (StringUtils.isNotBlank(eduBdSbjzz.getMotherIdcard())){
            eduBdSbjzz.setMotherJzz(BoolEnum.FALSE.getType());
            QueryWrapper<EduLivePlace> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(EduLivePlace::getSfzh,eduBdSbjzz.getMotherIdcard());
            List<EduLivePlace> list = eduLivePlaceService.list(queryWrapper);
            if (!ObjectUtils.isEmpty(list)){
                for (EduLivePlace eduLivePlace : list) {
                    String qzrq = eduLivePlace.getQzrq();
                    try {
                        Date qzrqDate = dateFormat.parse(qzrq);
                        Date compareDate = dateFormat.parse(compareDateStr);
                        if (qzrqDate.compareTo(compareDate) >= 0) {
                            //表示居住证有效
                            eduBdSbjzz.setMotherJzz(BoolEnum.TRUE.getType());
                            break;
                        }
                    } catch (ParseException e) {

                    }
                }
            }
            if (BoolEnum.FALSE.getType().equalsIgnoreCase(eduBdSbjzz.getMotherJzz())){
                //去调用大数据接口查询
                List<DyJzzVO> dyJzz = dygxIntegration.getDyJzz(eduBdSbjzz.getMotherJzz(),ip);
                for (DyJzzVO dyJzzVO : dyJzz) {
                    String qzrq = dyJzzVO.getQzrq();
                    try {
                        Date qzrqDate = dateFormat.parse(qzrq);
                        Date compareDate = dateFormat.parse(compareDateStr);
                        if (qzrqDate.compareTo(compareDate) >= 0) {
                            //表示居住证有效
                            eduBdSbjzz.setMotherJzz(BoolEnum.TRUE.getType());
                            break;
                        }
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
